package com.whut.googleplay.http;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;

import java.io.IOException;

/**
 * ============================================================
 * <br/>
 * 作 者 :        xyb
 * <br/>
 * 版 本 :        1.0
 * <br/>
 * 创建日期 ：     2016-05-04 下午8:31
 * <br/>
 * 描 述 ：        HttpHelper只是负责接收json数据，解析式在protocol中完成
 * <br/>
 * 修订历史 ：
 * <br/>
 * ============================================================
 **/
public class HttpHelper {

    public static HttpResult get(String url) {
        HttpGet httpGet = new HttpGet(url);
        return execute(url, httpGet);
    }

    /**
     * 通过jsonStub网站获取数据
     * @param url
     * @param useJsonStub
     * @return
     */
    public static HttpResult get(String url,boolean useJsonStub){
        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeader("JsonStub-User-Key", "0a0d2a98-1798-4349-9f3a-c2a6dc5b117c");
        httpGet.setHeader("JsonStub-Project-Key","54638332-f2d0-48b0-a3e4-03c952fa54b0");
        httpGet.setHeader("Content-Type","application/json;charset=UTF-8");
        return execute(url, httpGet);
    }

    private static HttpResult execute(String url, HttpRequestBase requestBase){
        boolean isHttps = url.startsWith("https://");
        AbstractHttpClient httpClient = (AbstractHttpClient)HttpClientFactory.create(isHttps);
        HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
        HttpRequestRetryHandler handler = httpClient.getHttpRequestRetryHandler();
        int retryCount = 0;
        boolean retry = true;
        while (retry){
            try
            {
                HttpResponse response = httpClient.execute(requestBase, httpContext);
                if(response != null){
                    return new HttpResult(httpClient,requestBase,response);
                }

            } catch (IOException e) {
                e.printStackTrace();
                retryCount++;
                retry = handler.retryRequest(e,retryCount,httpContext);
            }
        }
        return null;
    }
}
